using System;
using OTE.Tasks.Commands.Category;
using SharpArch.Domain.Commands;
using SharpArch.NHibernate.Contracts.Repositories;

namespace OTE.Tasks.CommandHandlers.Category
{
    public class CategoryUpdatedHandler : ICommandHandler<CategoryUpdatedCommand>
    {
        private readonly INHibernateRepository<Domain.Category> _categoryRepository;

        public CategoryUpdatedHandler(INHibernateRepository<Domain.Category> categoryRepository)
        {
            _categoryRepository = categoryRepository;
        }

        public ICommandResult Handle(CategoryUpdatedCommand command)
        {
            var uow = _categoryRepository.DbContext;

            var cat = _categoryRepository.Get(command.CategoryId);

            if (cat != null)
            {
                cat.Name = command.ContentName;

                var parent = _categoryRepository.Get(command.ParentId);

                cat.Parent = parent;

                cat.ModifiedDate = DateTime.Now;
            }

            cat = _categoryRepository.SaveOrUpdate(cat);

            uow.CommitChanges();

            var result = cat == null
                ? new CategoryUpdatedResult(false)
                : new CategoryUpdatedResult(true) { Category = cat };

            return result;
        }
    }
}